package com.xyhuo.leetcode.january;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 最长连续序列
 * https://leetcode.cn/problems/longest-consecutive-sequence/
 *
 * @time 2024/1/12
 */
public class LongestConsecutive {

    public int longestConsecutive(int[] nums) {
        int ans = 0;
        Map<Integer, Set<Integer>> map = new HashMap<>();
        for (int num : nums) {
            if (map.containsKey(num)) {
                continue;
            }
            if (!map.containsKey(num - 1) && !map.containsKey(num + 1)) {
                Set<Integer> set = new HashSet<>();
                set.add(num);
                map.put(num, set);
            } else if (map.containsKey(num - 1) && map.containsKey(num + 1)) {
                Set<Integer> num1 = map.get(num - 1);
                Set<Integer> num2 = map.get(num + 1);
                Set<Integer> newSet = new HashSet<>();
                newSet.addAll(num1);
                newSet.addAll(num2);
                newSet.add(num);
                newSet.forEach(e -> {
                    map.put(e, newSet);
                });
            } else if (map.containsKey(num - 1) && !map.containsKey(num + 1)) {
                Set<Integer> set = map.get(num - 1);
                set.add(num);
                map.put(num, set);
            } else {
                Set<Integer> set = map.get(num + 1);
                set.add(num);
                map.put(num, set);
            }
            if (map.get(num).size() > ans) {
                ans = map.get(num).size();
            }
        }
        return ans;
    }
}
